package com.woniu.liuzhougov.authorityControl.controller;

import com.github.pagehelper.PageInfo;
import com.woniu.liuzhougov.authorityControl.pojo.Role;
import com.woniu.liuzhougov.authorityControl.service.RoleRightsService;
import com.woniu.liuzhougov.authorityControl.service.RoleService;
import com.woniu.liuzhougov.authorityControl.service.UserRoleService;
import com.woniu.liuzhougov.authorityControl.utils.TableResult;
import com.woniu.liuzhougov.authorityControl.utils.TreeNode;
import com.woniu.liuzhougov.authorityControl.utils.TreeResult;
import com.woniu.liuzhougov.authorityControl.verification.AddRole;
import com.woniu.liuzhougov.authorityControl.verification.EditRole;
import com.woniu.liuzhougov.common.utils.Result;
import com.woniu.liuzhougov.common.utils.ValidatedResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * @version 1.0
 * @Author zhuxinpan
 * @ClassName RoleController
 * @Description 处理关于角色的请求
 * @Date 2019/4/26 9:56
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Resource
    private RoleService roleService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleRightsService roleRightsService;

    /**
     * @param currentPage
     * @param pageSize
     * @return com.woniu.liuzhougov.authorityControl.utils.TableResult<com.woniu.liuzhougov.authorityControl.pojo.Role>
     * @author zhuxinpan
     * @date 2019/4/26 11:36
     * @description
     */
    @RequestMapping("/listRoles")
    @ResponseBody
    public TableResult<Role> listRoles(@RequestParam(required = false, defaultValue = "1", name = "page") Integer currentPage, @RequestParam(required = false, defaultValue = "5", name = "limit") Integer pageSize) {
        List<Role> roleList = roleService.listRoles(currentPage, pageSize);
        PageInfo<Role> pageInfo = new PageInfo<>(roleList);
        TableResult<Role> tableResult = TableResult.getTableResult(roleList, pageInfo.getTotal());
        return tableResult;
    }

    /**
     * @param
     * @return java.lang.String
     * @author zhuxinpan
     * @date 2019/4/26 15:14
     * @description 跳转到添加角色界面
     */
    @RequiresPermissions(value = "role_addRole")
    @GetMapping("/addRole")
    public String addRole() {
        return "role_manager_addRole";
    }

    /**
     * @param role
     * @param bindingResult
     * @return com.woniu.liuzhougov.common.utils.Result
     * @author zhuxinpan
     * @date 2019/4/26 15:54
     * @description 添加角色
     */
    @RequiresPermissions(value = "role_addRole")
    @PostMapping(value = "/addRole")
    @ResponseBody
    public Result addRole(@Validated(value = AddRole.class) Role role, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.error(ValidatedResult.getValidateMessage("添加角色失败!", bindingResult));
        }
        if ("".equals(role.getRoleName().trim())) {
            return Result.error("角色名不能为空!");
        }
        if (roleService.countNumberByRoleName(role) > 0) {
            return Result.error("该角色已存在!");
        }
        if (roleService.addRole(role) == 0) {
            return Result.error("添加角色失败");
        }
        return Result.success("添加角色成功!");
    }

    /**
     * @param roleId
     * @param model
     * @return java.lang.String
     * @author zhuxinpan
     * @date 2019/4/27 21:58
     * @description 跳转到编辑角色页面
     */
    @RequiresPermissions("role_editRole")
    @GetMapping("/editRole/{roleId}")
    public String editRole(@PathVariable(name = "roleId") Integer roleId, Model model) {
        Role role = roleService.getRoleByRoleId(roleId);
        model.addAttribute("role", role);
        return "role_manager_editRole";
    }

    /**
     * @param role
     * @param bindingResult
     * @return com.woniu.liuzhougov.common.utils.Result
     * @author zhuxinpan
     * @date 2019/4/27 22:10
     * @description 编辑角色
     */
    @RequiresPermissions("role_editRole")
    @PostMapping(value = "/editRole")
    @ResponseBody
    public Result editRole(@Validated(value = EditRole.class) Role role, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.error(ValidatedResult.getValidateMessage("编辑角色失败!", bindingResult));
        }
        if ("".equals(role.getRoleName().trim())) {
            return Result.error("角色名不能为空!");
        }
        if (roleService.countNumberByRoleName(role) > 0) {
            return Result.error("该角色名重复!");
        }
        if (roleService.updateRole(role) == 0) {
            return Result.error("修改角色失败!");
        }
        return Result.success("修改角色成功!");
    }

    /**
     * @param roleId
     * @return com.woniu.liuzhougov.common.utils.Result
     * @author zhuxinpan
     * @date 2019/4/27 22:27
     * @description 删除角色
     */
    @RequiresPermissions("role_deleteRole")
    @DeleteMapping("/deleteRole/{roleId}")
    @ResponseBody
    public Result deleteRole(@PathVariable(name = "roleId") Integer roleId) {
        if (userRoleService.countRecordByRoleId(roleId) > 0) {
            return Result.error("该角色正在被使用,不能删除!");
        }
        if (roleService.deleteRoleByRoleId(roleId) == 0) {
            return Result.error("删除角色失败");
        }
        return Result.success("删除角色成功");
    }


    /**
     * @param userId
     * @param model
     * @return java.lang.String
     * @author zhuxinpan
     * @date 2019/4/28 17:46
     * @description 跳转到设置角色界面
     */
    @RequiresPermissions("role_setRole")
    @GetMapping("/setRole/{userId}")
    public String setRole(@PathVariable(name = "userId") Integer userId, Model model) {
        List<Role> roleList = roleService.listRoles();
        List<TreeNode> treeNodeList = new ArrayList<>();
        roleList.forEach(role -> treeNodeList.add(new TreeNode(role.getRoleId(), role.getRoleName(), 0)));
        List<Integer> roleCheckedList = userRoleService.listRoleIdByUserId(userId);
        Integer[] checkedId = new Integer[roleCheckedList.size()];
        roleCheckedList.toArray(checkedId);
        Map<String, Object> data = new HashMap<>();
        data.put("list", treeNodeList);
        data.put("checkedId", checkedId);
        model.addAttribute("treeResult", TreeResult.getTreeResult(data));
        model.addAttribute("userId", userId);
        return "account_manager_setRole";
    }

    /**
     * @param userId
     * @param roleIds
     * @return com.woniu.liuzhougov.common.utils.Result
     * @author zhuxinpan
     * @date 2019/4/29 20:34
     * @description 设置角色
     */
    @RequiresPermissions("role_setRole")
    @PostMapping("/setRole")
    @ResponseBody
    public Result setRole(Integer userId, Integer[] roleIds) {
        if (roleIds == null) {
            roleIds = new Integer[0];
        }
        if (userRoleService.setRole(userId, roleIds) == 0) {
            return Result.error("设置角色失败");
        }
        return Result.success("设置角色成功");
    }

    /**
     * @param
     * @return java.lang.String
     * @author zhuxinpan
     * @date 2019/5/5 14:56
     * @description 跳转到角色管理页面
     */
    @RequiresPermissions("role_manager")
    @GetMapping("/manager")
    public String manager() {
        return "role_manager";
    }
}
